package com.hospital.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hospital.configure.Result;
import com.hospital.entity.Registered;
import com.hospital.entity.User;
import com.hospital.mapper.RegisteredMapper;
import com.hospital.mapper.UserMapper;
import com.hospital.service.UserService;
import com.hospital.utils.IDGenerator;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    UserMapper userMapper;

    @Resource
    RegisteredMapper registeredMapper;

    @Override
    public Result<User> updateUser(User user) {
        Result<User> result = new Result<>();
        try {
            if (StringUtils.isEmpty(user.getUserId())) {
                //如果ID为空，代表添加
                user.setUserId(IDGenerator.getUUID("USER"));
                user.setCreateTime(new Date());
                user.setUserStatus("1");
                userMapper.insert(user);
            } else {
                //如果ID不为空，代表修改
                userMapper.updateById(user);
            }
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<User> delUser(User user) {
        Result<User> result = new Result<>();
        try {
            if (StringUtils.isEmpty(user.getUserId())) {
                result.setMessage("userId can't be empty");
                return result;
            }
            userMapper.deleteById(user.getUserId());
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<User> batchDelUser(User user) {
        Result<User> result = new Result<>();
        try {
            if (!StringUtils.isEmpty(user.getIds())) {
                String[] ids = user.getIds().split(",");
                for (String id : ids) {
                    userMapper.deleteById(id);
                }
            }
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<User> queryUser(User user) {
        Result<User> result = new Result<>();
        try {
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            //查询条件拼接，仅限单表查询可用
            if(!StringUtils.isEmpty(user.getUserAccount())){
                wrapper.lambda().eq(User::getUserAccount, user.getUserAccount());
            }
            if(!StringUtils.isEmpty(user.getUserName())){
                wrapper.lambda().like(User::getUserName, user.getUserName());
            }
            if(!StringUtils.isEmpty(user.getUserType())){
                wrapper.lambda().eq(User::getUserType, user.getUserType());
            }

            List<User> users = userMapper.selectList(wrapper);
            result.setReturnList(users);
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<User> queryUserByPage(User user) {
        Result<User> result = new Result<>();

        try {
            if (user.getCurrent() == null || user.getSize() == null) {
                result.setMessage("current or size can't be null");
                return result;
            }

            QueryWrapper<User> wrapper = new QueryWrapper<>();
            //查询条件拼接，仅限单表查询可用
            if(!StringUtils.isEmpty(user.getUserAccount())){
                wrapper.lambda().eq(User::getUserAccount, user.getUserAccount());
            }
            if(!StringUtils.isEmpty(user.getUserName())){
                wrapper.lambda().like(User::getUserName, user.getUserName());
            }
            if(!StringUtils.isEmpty(user.getUserType())){
                wrapper.lambda().eq(User::getUserType, user.getUserType());
            }
            //前端传了当前登录人，也就是医生的ID。放在createUser这个字段中了。
            if(!StringUtils.isEmpty(user.getCreateUser())){
                //先查询挂号表，查询医生ID为前端传过来的
                QueryWrapper<Registered> registeredQueryWrapper = new QueryWrapper<>();
                registeredQueryWrapper.lambda().eq(Registered::getDoctorId,user.getCreateUser());
                List<Registered> registeredList = registeredMapper.selectList(registeredQueryWrapper);
                //查询到一堆患者集合，用了java8的流式操作，把这个患者集合整理为一个去重的userId  集合
                Set<String> collect = registeredList.stream().map(item -> item.getUserId()).collect(Collectors.toSet());
                //然后查询用户ID在这个userID集合中的用户即可
                wrapper.lambda().in(User::getUserId,collect);
            }
            IPage<User> users = userMapper.selectPage(new Page<>(user.getCurrent(), user.getSize()), wrapper);
            result.setReturnPage(users);
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<User> queryUserById(User user) {
        Result<User> result = new Result<>();
        try {
            User returnUser = userMapper.selectById(user.getUserId());
            result.setReturnObj(returnUser);
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<User> checkUserInfo(User user) {
        Result<User> result = new Result<>();
        try {
            User returnUser = userMapper.selectById(user.getUserId());
            if(user.getIdentity() != null && user.getIdentity().equals(returnUser.getIdentity())){
                userMapper.updateById(user);
                result.setMessage("success");
            }else{
                result.setMessage("success");
                result.setCode("userInfoError");
            }
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }
}
